#include <BearSSLHelpers.h>
#include <CertStoreBearSSL.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiAP.h>
#include <ESP8266WiFiGeneric.h>
#include <ESP8266WiFiGratuitous.h>

/*#include <ESP8266WiFiMulti.h>
#include <ESP8266WiFiScan.h>
#include <ESP8266WiFiSTA.h>
#include <ESP8266WiFiType.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <WiFiClientSecureAxTLS.h>
#include <WiFiClientSecureBearSSL.h>
#include <WiFiServer.h>
#include <WiFiServerSecure.h>
#include <WiFiServerSecureAxTLS.h>
#include <WiFiServerSecureBearSSL.h>
#include <WiFiUdp.h>
*/
#include <ESP8266WiFi.h>
//#include "esp_camera.h"
#include <WiFiClient.h>
#include <ArduinoJson.h>

//平台接入服务器地址ndp.nlecloud.com或IP 117.78.1.201
#define TCP_SERVER_ADDR "ndp.nlecloud.com"
//服务器端口，tcp新大陆物联TCP端口8600,8700,8800
#define TCP_SERVER_PORT "8600"

//WIFI名称，区分大小写，不要写错  
#define DEFAULT_STASSID  "nan"   //修改为自己WIFI
//WIFI密码
#define DEFAULT_STAPSW   "12345678"


//设置上传速率5s（1s<=upDataTime<=60s）
#define upDataTime 5*1000

//最大字节数
#define MAX_PACKETSIZE 512
//设置心跳值10s
#define KEEPALIVEATIME 10*1000

//tcp客户端相关初始化，默认即可
WiFiClient TCPclient;
String TcpClient_Buff = "";
unsigned int TcpClient_BuffIndex = 0;
unsigned long TcpClient_preTick = 0;
unsigned long preHeartTick = 0;//心跳
unsigned long preTCPStartTick = 0;//连接
bool preTCPConnected = false;

//相关函数初始化
//连接WIFI
void doWiFiTick();
void startSTA();

//TCP初始化连接
void doTCPClientTick();
void startTCPClient();
void sendtoTCPServer(String p);

//led 控制函数
void turnOnLed();
void turnOffLed();
//继电器
void turnOnLed1();
void turnOffLed1();

/*
  *发送数据到TCP服务器
 */
void sendtoTCPServer(String p)
{
  if (!TCPclient.connected()) 
  {
    Serial.println("Client is not readly");
    return;
  }
  TCPclient.print(p);
  Serial.println("[Send to TCPServer]:String");
  Serial.println(p);
}

/*
  *初始化和服务器建立连接
*/
void startTCPClient()
{
  if(TCPclient.connect(TCP_SERVER_ADDR, atoi(TCP_SERVER_PORT)))
  {
    Serial.print("\nConnected to server:");
    Serial.printf("%s:%d\r\n",TCP_SERVER_ADDR,atoi(TCP_SERVER_PORT));
    DynamicJsonDocument doc(256);
    // 替换成自己的
    String Start_put = "{\"t\":\"1\",\"device\":\"camera1\",\"Key\":\"fce6b6b19e454dff8e552ccd47c0f6a2\",\"ver\":\"v1.1\"}"; //替换成自己的
    deserializeJson(doc, Start_put);  //创建数据
    sendtoTCPServer(Start_put);
    preTCPConnected = true;
    preHeartTick = millis();
    TCPclient.setNoDelay(true);
  }
  else
  {
    Serial.print("Failed connected to server:");
    Serial.println(TCP_SERVER_ADDR);
    TCPclient.stop();
    preTCPConnected = false;
  }
  preTCPStartTick = millis();
}

/*
  *检查数据，发送心跳
*/
void doTCPClientTick()
{
 //检查是否断开，断开后重连
  if(WiFi.status() != WL_CONNECTED) 
  return;

  if (!TCPclient.connected()) 
  {//断开重连

    if(preTCPConnected == true)
    {
      preTCPConnected = false;
      preTCPStartTick = millis();
      Serial.println();
      Serial.println("TCP Client disconnected.");
      TCPclient.stop();
    }
    else if(millis() - preTCPStartTick > 1*1000)//重新连接
    startTCPClient();
  }
  else
  {
    if (TCPclient.available()) //收数据
    {
      char c =TCPclient.read();
      TcpClient_Buff +=c;
      TcpClient_BuffIndex++;
      TcpClient_preTick = millis();
      
      if(TcpClient_BuffIndex>=MAX_PACKETSIZE - 1)
      {
        TcpClient_BuffIndex = MAX_PACKETSIZE-2;
        TcpClient_preTick = TcpClient_preTick - 200;
      }
      preHeartTick = millis();
    }
    if(millis() - preHeartTick >= KEEPALIVEATIME)//保持心跳
    {
      preHeartTick = millis();
      Serial.println("--Keep alive:");
      sendtoTCPServer("$#AT#\r\n");
    }
  }
  if((TcpClient_Buff.length() >= 1) && (millis() - TcpClient_preTick>=200))
  {//data ready
    TCPclient.flush();
    Serial.println("Buff");
    Serial.println(TcpClient_Buff);

    TcpClient_Buff="";
    TcpClient_BuffIndex = 0;
  }

  //上传数据
  //DTH11上传数据
   if (millis() - preHeartTick >= upDataTime) 
   { //上传数据
      preHeartTick = millis();

      /*********************数据上传*******************/
      
      DynamicJsonDocument doc(1024);
      const char* url="https://img.bemfa.com/9d506202bc684bb74c27216969e3a13f-9cbb8eaa35a7af3b05db7dffa391c67a-1616647580.jpg";
      const char ch = '-';
      char *ret;
      ret = strchr(url, ch);
      String input = "{\"t\":\"3\",\"datatype\":1,\"datas\":{\"camera\":ret}}";
      
      Serial.println(url);
      deserializeJson(doc, input);  //创建数据
      //Serial.println(input);
      JsonObject obj = doc.as<JsonObject>();

       obj["datas"]["camera"] = ret;
       String output;
       serializeJson(doc, output);
       sendtoTCPServer(output);
       //Serial.println(output);
    }
}

void startSTA(){
  WiFi.disconnect();
  WiFi.mode(WIFI_STA);
  WiFi.begin(DEFAULT_STASSID, DEFAULT_STAPSW);

}

/**************************************************************************
                                 WIFI
***************************************************************************/
/*
  WiFiTick
  检查是否需要初始化WiFi
  检查WiFi是否连接上，若连接成功启动TCP Client
  控制指示灯
*/
void doWiFiTick(){
  static bool startSTAFlag = false;
  static bool taskStarted = false;
  static uint32_t lastWiFiCheckTick = 0;

  if (!startSTAFlag) 
  {
    startSTAFlag = true;
    startSTA();
    Serial.printf("Heap size:%d\r\n", ESP.getFreeHeap());
  }

  //未连接1s重连
  if ( WiFi.status() != WL_CONNECTED ) 
  {
    if (millis() - lastWiFiCheckTick > 1000) 
    {
      lastWiFiCheckTick = millis();
    }
  }
  //连接成功建立
  else 
  {
    if (taskStarted == false) 
    {
      taskStarted = true;
      Serial.print("\r\nGet IP Address: ");
      Serial.println(WiFi.localIP());
      startTCPClient();
    }
  }
}

// 初始化，相当于main 函数
void setup() 
{
  Serial.begin(115200);
}

//循环
void loop() 
{
  doWiFiTick();
  doTCPClientTick();
}
